<?php
include_once (SERVER_ROOT_PATH . '/Inc/Lib/Openapi/Openapi_renren.php');
class ml_model_openapiRenren extends Lib_openapi_abstract {
    /*
     * 检测返回code
     */
    public function check_auth($code) {
        $redirect_uri = urlencode ( OPENAPI_CALLBACK_URL . "?type=renren" );
        $url = 'https://graph.renren.com/oauth/token?grant_type=authorization_code&client_id=' . OPENAPI_RENREN_APP_KEY . '&redirect_uri=' . $redirect_uri . '&client_secret=' . OPENAPI_RENREN_APP_TOKEN . '&code=' . $code;
        $return = Tool_http::get ( $url );
        $arr = json_decode ( $return, 1 );
        $session = ml_controller::getSession ();
        $session->setVal ( 'access_token', $arr ['access_token'] );
        $session->setVal ( 'token_secret', $arr ['refresh_token'] );
        $session->setVal ( '3rd_id', $arr ['user'] ['id'] );
        $session->save ();
        return $arr;
    }
    
    /*
     * 获取授权用链接
     */
    public function get_auth_url() {
        $redirect_uri = urlencode ( OPENAPI_CALLBACK_URL . "?type=renren" );
        return $url = 'https://graph.renren.com/oauth/authorize?client_id=' . OPENAPI_RENREN_APP_KEY . '&redirect_uri=' . $redirect_uri . '&response_type=code';
    }
    
    /*
     * 获取用户基本信息
     */
    public function get_user_info() {
        $session = ml_controller::getSession ();
        $openapi = new RenrenRestApiService ();
        $params = array (
                'fields' => 'uid,name,sex,birthday,mainurl', 
                'access_token' => $session->getVal ( 'access_token' ) 
        );
        $return = $openapi->rr_post_curl ( 'users.getInfo', $params );
        $userinfo = array ();
        $userinfo ['nickname'] = $return [0] ['name'];
        $userinfo ['gender'] = $return [0] ['sex'] == 1 ? 'm' : 'f';
        $userinfo ['birthday'] = $return [0] ['birthday'] < '1800-01-01' ? '' : $return ['birthday'];
        /* $userinfo ['province_id'] = '';
        $userinfo ['city_id'] = ''; */
        $userinfo ['head_url'] = $return [0] ['mainurl'];
        return $userinfo;
    }
    
    /*
     * (non-PHPdoc) @see Lib_openapi_abstract::sent_message()
     */
    public function sent_message() {
    
    }

}
